/* $Id:item_spell.cc $ */
/*
   Copyright (C) 2007 by Jurjen Stellingwerff <jurjen@stwerff.xs4all.nl>
   Part of the Moros Project http://moros.sourceforge.net/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 3.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#define DEBUG_ROUTINE "item_spell"

#include <sstream>
#include <fstream>
#include "../general/util.h"
#include "../general/log.h"
#include "../general/channel.h"
#include "item_spell.h"
#include "action.h"
#include "../general/general.h"

item_spell::item_spell() {
    spell=0;
    level=0;
    type=-1;
}

// Field : spell

class action& item_spell::getSpell() const { if (spell==0) throw nullpointer(); return *spell; }
void item_spell::setSpell(class action &v) { spell=&v; }

// Field : level

const int item_spell::getLevel() const { return level; }
void item_spell::setLevel(const int v) { level=v; }

// Field : type

const string item_spellType[]={"continues","on_hit","single_use"};
const int item_spell::getType() const { return type; }
const string item_spell::showType() const {
    if (type<0) return "";
    else return item_spellType[type];
}
void item_spell::setType(const int  v) {
    if (v<0 || (unsigned int)v >= sizeof item_spellType/sizeof item_spellType[0]) type=-1;
    else type=v;
}
void item_spell::setType(const string v) {
    type=-1;
    loopArray(item_spellType, tp, string) {
        if (v==*tp) {type=tp_i; break; }
    }
    if (type==-1) dbg_state("Enumerate item_spell.type %s has unknown '%s'", getSpell().getName().c_str(), v.c_str());
}

void item_spell::save(class channel &ch) {
    ch.write("item_spell", "");
    ch.write("s", getSpell().getName());
    ch.write("l", getLevel());
    ch.write("t", getType());
}

void item_spell::load(class channel &ch) {
    if (ch.key=="s" || ch.key=="spell") {
        if (!action_repo.isAction(ch.value)) {
            dbg_state("link unknown action %s", ch.value.c_str());
            class action rec;
            rec.setName(ch.value);
            action_repo.setAction(rec);
        }
        setSpell(action_repo.getAction(ch.value));
        ch.next();
    }
    if (ch.key=="l" || ch.key=="level") { setLevel(atoi(ch.value.c_str())); ch.next(); }
    if (ch.key=="t" || ch.key=="type") { setType(ch.value); ch.next(); }
}

void item_spell::xml(ofstream &f, int l, int r) {
    f << ncpy(l, "  ") << "<item_spell level=\"" << getLevel() <<
    "\" type=\"" << showType() <<
    "\">" << endl;
    if (r<2) try {
        getSpell().xml(f,l+1,r+1);
    } catch (nullpointer n) {}
    f << ncpy(l, "  ") << "</item_spell>" << endl;
}
